<script setup lang="ts">

import {showSimpleDialog} from "@/utils/dialog-utils.ts";
import {ref} from "vue";
import {
  bindRolePermissions,
  deleteRole, getAllPermissions,
  getAllRoles,
  getEmptyRole, getRolePermissions,
  Permission,
  Role,
  saveOrUpdateRole, unbindRolePermissions
} from "@/net/controller/rbac-controller.ts";

/**
 * 权限列表
 */
const permissions = ref<Permission[]>([])

async function refreshPermissions() {
  permissions.value = await getAllPermissions()
}

refreshPermissions()

/**
 * 角色列表
 */
const roles = ref<Role[]>([])
const rolePermissions = ref<Map<Number, Permission[]>>(new Map())

async function refreshData() {
  roles.value = await getAllRoles()
  for (const role of roles.value) {
    rolePermissions.value.set(role.roleId, (await getRolePermissions(role.roleId)).data)
  }
}

refreshData()

/**
 * 角色编辑对话框
 */
const showEditorDialog = ref(false)
const editorDialogData = ref<Role>(getEmptyRole())

function openEditorDialog(role: Role) {
  showEditorDialog.value = true
  editorDialogData.value = role
}

function onEditorDialogSaveConfirmed() {
  saveOrUpdateRole(editorDialogData.value).then(() => {
    ElMessage.success("保存成功")
    showEditorDialog.value = false
    refreshData()
  })
}

function onDelete(role: Role) {
  showSimpleDialog(`删除 ${role.name}`, `是否要删除角色 ${role.name}`, () => {
    deleteRole(role.roleId).then(() => {
      ElMessage.success("删除成功")
      refreshData()
    })
  })
}

/**
 * 角色-权限绑定对话框
 */
const showRolePermissionBindingDialog = ref(false)
const rolePermissionBindingDialogData = ref<{roleId: number, permissionId: number}>({ roleId: 0, permissionId: 0 })

function openRolePermissionBindingDialog(role: Role) {
  showRolePermissionBindingDialog.value = true
  rolePermissionBindingDialogData.value = {
    roleId: role.roleId,
    permissionId: 0
  }
}

function onRolePermissionBindConfirm() {
  bindRolePermissions(rolePermissionBindingDialogData.value.roleId, rolePermissionBindingDialogData.value.permissionId).then(() => {
    ElMessage.success("添加成功")
  }).finally(() => {
    showRolePermissionBindingDialog.value = false
    refreshData()
  })
}

function onUnbindRolePermission(role: Role, permission: Permission) {
  showSimpleDialog(`解绑权限 ${permission.name}`, `是否要将权限 ${permission.name} 从角色 ${role.name} 中移除?`, () => {
    unbindRolePermissions(role.roleId, permission.permissionId).then(() => {
      ElMessage.success("删除成功")
      refreshData()
    })
  })
}
</script>

<template>
  <main>
    <div>
      <el-button size="default" type="info" @click="refreshData()">刷新</el-button>
      <el-button size="default" type="primary" @click="openEditorDialog(getEmptyRole())">添加</el-button>
    </div>

    <el-table :data="roles" style="width: 100%; margin-top: 1rem">
      <!-- 角色权限表格 -->
      <el-table-column type="expand">
        <template #default="props">
          <div class="flex flex-vertical" style="padding: 1rem">
            <div class="flex flex-horizontal">
              <el-button size="small" type="primary" @click="openRolePermissionBindingDialog(props.row)">添加</el-button>
            </div>

            <el-table style="margin-top: 1rem" :data="rolePermissions.get(props.row.roleId)">
              <el-table-column label="权限ID" prop="permissionId" />
              <el-table-column label="权限名称" prop="name" />
              <el-table-column fixed="right" label="操作" min-width="120">
                <template #default="scope">
                  <el-button link type="danger" size="small" @click="onUnbindRolePermission(props.row, scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="roleId" label="角色ID" width="120" />
      <el-table-column prop="name" label="名称" />

      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="openEditorDialog(scope.row)">
            编辑
          </el-button>
          <el-button link type="danger" size="small" @click="onDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="showEditorDialog" title="添加/编辑角色" width="600">
      <el-form size="default" :model="editorDialogData" label-width="auto" style="max-width: 600px" label-position="top">
        <el-form-item label="角色名称">
          <el-input v-model="editorDialogData.name" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div>
          <el-button size="default" @click="showEditorDialog = false">取消</el-button>
          <el-button size="default" type="primary" @click="onEditorDialogSaveConfirmed()">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="showRolePermissionBindingDialog" title="绑定权限" width="450">
      <el-select
          v-model="rolePermissionBindingDialogData.permissionId"
          placeholder="Select"
          size="large"
          style="width: 240px"
      >
        <el-option
            v-for="item in permissions"
            :key="item.name"
            :label="item.name"
            :value="item.permissionId"
        />
      </el-select>

      <template #footer>
        <div>
          <el-button size="default" @click="showRolePermissionBindingDialog = false">取消</el-button>
          <el-button size="default" type="primary" @click="onRolePermissionBindConfirm()">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </main>
</template>

<style scoped>

</style>